<template>
  <view class="avatar-wrapper" :style="{ width: size, height: size }">
    <image class="avatar-image" :src="avatarSrc" :mode="mode" @error="onImageError" />
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { baseConfig } from '@/http/request'

const props = defineProps({
  // 头像URL
  src: {
    type: String,
    default: ''
  },
  // 头像大小
  size: {
    type: String,
    default: '110rpx'
  },
  // 图片模式
  mode: {
    type: String,
    default: 'aspectFit'
  },
  // 是否为圆形
  round: {
    type: Boolean,
    default: true
  }
})

const imageError = ref(false)

// 计算头像源地址
const avatarSrc = computed(() => {
  if (imageError.value || !props.src) {
    return '/static/icon/defaultAvatar.png'
  }

  // 如果是完整的URL，直接返回
  if (props.src.startsWith('http')) {
    return props.src
  }

  // 如果是相对路径，拼接baseURL
  return `${baseConfig.uploadURL}${props.src}`
})

// 图片加载失败处理
const onImageError = () => {
  imageError.value = true
}
</script>

<style lang="scss" scoped>
.avatar-wrapper {
  overflow: hidden;
  background-color: #f9f9f9;
  border-radius: 50%;

  .avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.avatar-wrapper.square {
  border-radius: 8rpx;
}
</style>
